package com.ece.devirtualizus.Dao;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.util.Log;

import com.ece.devirtualizus.ModelDto.GpsPositionDto;

public class SqlLiteGpsPositionDao {
	private SQLiteDatabase database;
	private SqlLiteGpsPositionHelper dbHelper;
	SimpleDateFormat dateFormat;
	Context context;
	private String[] allColumns = { SqlLiteGpsPositionHelper.COLUMN_ID,
			SqlLiteGpsPositionHelper.COLUMN_LAT,
			SqlLiteGpsPositionHelper.COLUMN_LONG,
			SqlLiteGpsPositionHelper.COLUMN_DATE };

	public SqlLiteGpsPositionDao(Context context) {
		// TODO Auto-generated constructor stub
		this.dbHelper = new SqlLiteGpsPositionHelper(context);
		this.context = context;
		dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	}

	public void open() throws SQLException {
		boolean isOk = dbHelper.checkDataBase();
		if (isOk) {
			Log.w("SqlLiteGpsPositionDao.open", "return true");
			this.database = this.dbHelper.getWritableDatabase();
			this.dbHelper.onCreate(this.database);
		} else {
			Log.w("SqlLiteGpsPositionDao.open", "return false");
			this.database = this.dbHelper.getReadableDatabase();
		}
	}

	public void close() {
		this.dbHelper.close();
	}

	public long createGpsPosition(GpsPositionDto position) {
		ContentValues values = new ContentValues();
		values.put(SqlLiteGpsPositionHelper.COLUMN_LAT, position.getLocation()
				.getLatitude());
		values.put(SqlLiteGpsPositionHelper.COLUMN_LONG, position.getLocation()
				.getLongitude());
		values.put(SqlLiteGpsPositionHelper.COLUMN_DATE,
				dateFormat.format(position.getDate()));
		long rowId = 0;
		try {
			rowId = this.database.insert(
					SqlLiteGpsPositionHelper.TABLE_GPS_POSITION, null, values);
			Log.i("SqlLiteGpsPositionDao.createGpsPosition--fin", "rowId:" + rowId);

		} catch (Exception e) {
			Log.e("SqlLiteGpsPositionDao.insert", e.getMessage());

		}

		return rowId;
	}

	public ArrayList<GpsPositionDto> getAllCacheGpsPosition() {
		ArrayList<GpsPositionDto> gpsPositionList = new ArrayList<GpsPositionDto>();
		try {
			Log.i("getAllCacheGpsPosition -- debut", "");
			Cursor cursor = database.query(
					SqlLiteGpsPositionHelper.TABLE_GPS_POSITION, null,
					null, null, null, null, null);
			Log.i("cursor--postquery", "");

			cursor.moveToFirst();

			int i = 0;
			while (!cursor.isAfterLast()) {
				GpsPositionDto position = new GpsPositionDto();
				String dateformated = "";
				Location location = new Location("");

				location.setLatitude(cursor.getDouble((cursor
						.getColumnIndex(SqlLiteGpsPositionHelper.COLUMN_LAT))));
				location.setLongitude(cursor.getDouble(cursor
						.getColumnIndex(SqlLiteGpsPositionHelper.COLUMN_LONG)));	
				
				dateformated = cursor.getString(cursor
						.getColumnIndex(SqlLiteGpsPositionHelper.COLUMN_DATE));
				Date date=new Date();
				date=dateFormat.parse(dateformated);
				List<Address> address = getCityFromLocation(location);
				// date= new Date(format);
				position.setLocation(location);
				position.setDate(date);
				if(address.size()>0){
				position.setZipCode(address.get(0).getPostalCode());
				position.setCodeCountry(address.get(0).getCountryCode());
				position.setLocality(address.get(0).getLocality());
				position.setDate(date);
				}else{
					position.setZipCode("00000");
					position.setCodeCountry("NO COUNTRY");
					position.setLocality("XX");
				}
				gpsPositionList.add(position);
				cursor.moveToNext();
				i++;
			}
			cursor.close();
		} catch (Exception e) {
			Log.e("SqlLiteGpsPositionDao.query",
					e.getMessage() + ";" + e.getCause());
			return gpsPositionList;
		}
		Log.i("getAllCacheGpsPosition--fin",
				"list.size():" + gpsPositionList.size());

		if (gpsPositionList.size() > 0) {
			// this.dbHelper.destroyDatabase(this.database);
			this.dbHelper.truncateDatabase(this.database);
			Log.i("dbHelper.destroyDatabase--fin", "");

		}
		return gpsPositionList;
	}

	private GpsPositionDto convertCursorToGpsPositionDto(Cursor cursor) {
		// TODO Auto-generated method stub
		Log.d("SqlLiteGpsPositionDao.convertCursorToGpsPositionDto -- debut", "");

		GpsPositionDto position = new GpsPositionDto();
		String format = "";
		Location location = new Location("");

		location.setLatitude(cursor.getDouble((cursor
				.getColumnIndex(SqlLiteGpsPositionHelper.COLUMN_LAT))));
		location.setLongitude(cursor.getDouble(cursor
				.getColumnIndex(SqlLiteGpsPositionHelper.COLUMN_LONG)));
		format = cursor.getString(cursor
				.getColumnIndex(SqlLiteGpsPositionHelper.COLUMN_DATE));
		Date date = new Date();
		List<Address> address = getCityFromLocation(location);
		// date= new Date(format);
		position.setLocation(location);
		position.setDate(date);
		if(address.size()>0){
		position.setZipCode(address.get(0).getPostalCode());
		position.setCodeCountry(address.get(0).getCountryCode());
		position.setLocality(address.get(0).getLocality());
		}else{
			position.setZipCode("00000");
			position.setCodeCountry("NO COUNTRY");
			position.setLocality("XX");

		}
		Log.d("SqlLiteGpsPositionDao.convertCursorToGpsPositionDto.position", position.toString());
		return position;
	}

	private List<Address> getCityFromLocation(Location loc) {
		Geocoder geo = new Geocoder(context, Locale.FRANCE);
		String zipCode = "";
		List<Address> addr = new ArrayList<Address>();
		Address addrItem = null;
		try {
			addr = geo.getFromLocation(loc.getLatitude(), loc.getLongitude(), 2);
			Log.d("SqlLiteGpsPositionDao.getCityFromLocation", "addr:"+addr.size());

			// addrItem = (Address) geo.getFromLocation(loc.getLatitude(),
			// loc.getLongitude(), 1);
			// zipCode = addrItem.getPostalCode();
//			Log.i("getCityFromLocation", "addr.get(0).getLocality():" + addr.get(0).getLocality());
//			Log.i("getCityFromLocation", "addr.get(0).getCountryCode():" + addr.get(0).getCountryCode());
//			Log.i("getCityFromLocation", "addr.get(0).getCountryName():" + addr.get(0).getCountryName());
//			Log.i("getCityFromLocation", "addr.get(0).getSubLocality():" + addr.get(0).getSubLocality());
//			Log.i("getCityFromLocation", "addr.get(0).getLocale():" + addr.get(0).getLocale());

			return addr;
		} catch (Exception e) {
			Log.e("getCityFromLocation",
					"ECHEC geo.getFromLocation " + e.getMessage());
			return addr;
		}
	}

}
